package com.example.teesystem.common.config;

import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.example.teesystem.common.cache.CourseCache;
import com.example.teesystem.common.cache.IssueCache;
import com.example.teesystem.common.cache.UserCache;
import com.example.teesystem.entity.WebLog;
import com.example.teesystem.filter.MyHandlerInterceptor;
import com.example.teesystem.mapper.ExamPaperMapper;
import com.example.teesystem.service.LogService;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.math.BigInteger;
import java.util.*;

/**
 * 统一日志处理切面
 * Created by macro on 2018/4/26.
 */
@RequiredArgsConstructor
@Aspect
@Component
@Order(1)
public class WebLogAspect {
    private static final Logger LOGGER = LoggerFactory.getLogger(WebLogAspect.class);

    private final ExamPaperMapper examPaperMapper;
    private final LogService logService;

    @Pointcut("@annotation(io.swagger.annotations.ApiOperation)")
    public void webLog() {
    }

    @Before("webLog()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {
    }

    @AfterReturning(value = "webLog()", returning = "ret")
    public void doAfterReturning(Object ret) throws Throwable {
    }

    @Around("webLog()")
    public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
        Date date = new Date();
        BigInteger startTime = BigInteger.valueOf(date.getTime());
        //获取当前请求对象
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        //记录请求信息
        WebLog webLog = new WebLog();
        Object result = joinPoint.proceed();
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();

        Map<String,String[]> map = request.getParameterMap();
        System.out.println(map);

        webLog.setCourseId(0);
        JSON json = JSONUtil.parse(joinPoint.getArgs()[0]);
//        Integer courseId = null,issueId = (Integer) json.getByPath("issueId"),paperId = (Integer) json.getByPath("paperId");
//        courseId = (Integer) json.getByPath("courseId");
        String issue_id,paper_id,course_id = null;
        Integer issueId,paperId,courseId;
        ArrayList<String> arrayList = null;

        try{
            System.out.println("arraylist");
            arrayList = (ArrayList)json.getByPath("courseId");
            if(arrayList!=null){
                for (String s : arrayList) {
                    course_id = s;
                }
            }
        }catch (Exception e){
            System.out.println(e.getMessage());
            course_id = String.valueOf(json.getByPath("courseId"));
        }

        try{
            assert course_id != null;
            courseId = Integer.parseInt(course_id);
        }catch (Exception e){
            courseId = null;
        }

        try{
            issue_id = (String) json.getByPath("issueId");
            issueId = Integer.parseInt(issue_id);
        }catch (Exception e){
            issueId = null;
        }

        try{
            paper_id = (String) json.getByPath("paperId");
            paperId = Integer.parseInt(paper_id);
        }catch (Exception e){
            paperId = null;
        }

        if(map.containsKey("courseId")){
            courseId = Integer.parseInt(map.get("courseId")[0]);
            System.out.println("map:"+courseId);
        }

        if(courseId == null) {
            if (issueId != null) {
                courseId = IssueCache.issueMap.get(issueId);
                //               webLog.setCourseId(courseId);
            } else if (paperId != null) {
                courseId = examPaperMapper.getCourseIdByPaperId(paperId);
                //               webLog.setCourseId(courseId);
                }
        }

        if(courseId != null){
            if (CourseCache.courseMap.get(courseId) != null) {
                webLog.setCourseId(courseId);
                }
            }


        if (method.isAnnotationPresent(ApiOperation.class)) {
            ApiOperation apiOperation = method.getAnnotation(ApiOperation.class);
            webLog.setDescription(apiOperation.value());
        }
        webLog.setUsername(UserCache.userMap.get(MyHandlerInterceptor.getUid()).getMyName());
        webLog.setUserAccount(UserCache.userMap.get(MyHandlerInterceptor.getUid()).getAccount());
        webLog.setUserId(MyHandlerInterceptor.getUid());

        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }

        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }

        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }


        webLog.setIp(ip);
        webLog.setServiceTime(new Date());
        webLog.setUrl(request.getRequestURL().toString());

        logService.add(webLog);

        LOGGER.info("{}", JSONUtil.parse(webLog));
        return result;
    }

    /**
     * 根据方法和传入的参数获取请求参数
     */
    private Object getParameter(Method method, Object[] args) {
        List<Object> argList = new ArrayList<>();
        Parameter[] parameters = method.getParameters();
        for (int i = 0; i < parameters.length; i++) {
            //将RequestBody注解修饰的参数作为请求参数
            RequestBody requestBody = parameters[i].getAnnotation(RequestBody.class);
            if (requestBody != null) {
                argList.add(args[i]);
            }
            //将RequestParam注解修饰的参数作为请求参数
            RequestParam requestParam = parameters[i].getAnnotation(RequestParam.class);
            if (requestParam != null) {
                Map<String, Object> map = new HashMap<>();
                String key = parameters[i].getName();
                if (!StringUtils.isEmpty(requestParam.value())) {
                    key = requestParam.value();
                }
                map.put(key, args[i]);
                argList.add(map);
            }
        }
        if (argList.size() == 0) {
            return null;
        } else if (argList.size() == 1) {
            return argList.get(0);
        } else {
            return argList;
        }
    }
}

